package com.harassment.interception.interception.telephone;

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.harassment.interception.ui.fragments.setting.SettingFragment;


public class TelephoneInterceptionService extends Service {
    private static final String TAG = "TIService";
    private TelephoneStateListener mTelephoneStateListener;
    private TelephonyManager mTelephonyManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void startService(Context context, Intent intent) {
        Intent actionIntent = new Intent(context, TelephoneInterceptionService.class);
        actionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        actionIntent.setAction(intent.getAction());
        actionIntent.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
        actionIntent.putExtra(TelephonyManager.EXTRA_STATE, intent.getStringExtra(TelephonyManager.EXTRA_STATE));
        context.startService(actionIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        onHandleIntent(intent);
        return super.onStartCommand(intent, flags, startId);
    }

    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent: 当前线程:" + Thread.currentThread().getName());
        if (intent == null) {
            Log.d(TAG, "onHandleIntent: intent为null 结束方法!");
            return;
        }
        //检查拦截是否打开
        if (!SettingFragment.isIntercept()) {
            Log.d(TAG, "onHandleIntent: 拦截没打开");
            return;
        }
        if (mTelephonyManager == null) {
            Log.d(TAG, "onHandleIntent: 生成TelephoneManager");
            mTelephonyManager = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
        }
        if (mTelephoneStateListener == null) {
            Log.d(TAG, "onHandleIntent: 生成StateListener");
            mTelephoneStateListener = new TelephoneStateListener();
        }
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        Log.d(TAG, "onHandleIntent: number:"+number);
        Log.d(TAG, "onHandleIntent: state:"+state);
        mTelephoneStateListener.onCallStateChanged(state,number);
    }


}
